package com.dcm.oss.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import com.dcm.common.annotation.IgnoreResponseBodyAdvice;
import com.dcm.oss.config.OssConfig;
import com.dcm.oss.dto.OssCallbackParam;
import com.dcm.oss.dto.OssCallbackResult;
import com.dcm.oss.dto.OssPolicyResult;
import com.dcm.oss.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * [oss文件系统 实现类]
 *
 * @author : [pengrongsheng]
 * @createTime : [2021/3/28]
 */
@Service
@Slf4j
public class OssServiceImpl implements OssService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class);

    /**
     * 效验上传的格式
     */
    private static final List<String> UPLOAD_TYPE = Stream.of(".bmp", ".jpg", ".jpeg", ".gif", ".png").collect(Collectors.toList());

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;


    @Override
    public String uploadFile(MultipartFile multipartFile) {

        //2.生成oss服务器图片名称（这里用uuid拼接一个name，防止上传图片与其他图片重名而覆盖同名oss文件）
        String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + multipartFile.getOriginalFilename();
        // 通过UploadFileRequest设置多个参数
        UploadFileRequest uploadFileRequest = new UploadFileRequest(ossConfig.getBucketName(), fileName);
        // 指定上传的本地文件。
        uploadFileRequest.setUploadFile("D:\\OtherFiles\\表情包壁纸\\3d7a5a878d4992c6bac672b2544474d7.gif");
        // 指定上传并发线程数，默认为1。
        uploadFileRequest.setTaskNum(5);
        // 指定上传的分片大小。 1*1024*1024 (1M)
        uploadFileRequest.setPartSize(1024 * 1024);
        // 开启断点续传，默认关闭。
        uploadFileRequest.setEnableCheckpoint(true);

        try {
            // 断点续传上传。
            UploadFileResult uploadFileResult = ossClient.uploadFile(uploadFileRequest);
            CompleteMultipartUploadResult multipartUploadResult =
                    uploadFileResult.getMultipartUploadResult();
            System.out.println(multipartUploadResult.getETag());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
    }

    @Override
    public String putPic(MultipartFile multipartFile) {

        // 校验图片格式
        boolean isLegal = false;
        for (String type : UPLOAD_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }

        if (!isLegal) {
            return "上传格式不支持...";
        }

        String picUrl = "";
        try {
            //1.图片文件
            //2.生成oss服务器图片名称（这里用uuid拼接一个name，防止上传图片与其他图片重名而覆盖同名oss文件）
            String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + multipartFile.getOriginalFilename();
            ByteArrayInputStream in = new ByteArrayInputStream(multipartFile.getBytes());
            // 填写Bucket名称、Object完整路径和本地文件的完整路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), fileName, in);
            //3.上传到oss服务器
            // 上传Object
            ossClient.putObject(putObjectRequest);
            // 关闭ossClient
            ossClient.shutdown();

            //返回oss服务器访问上传图片的url
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
        } catch (Exception e) {
            log.error("picture upload failed. error:", e);
        }
        return picUrl;
    }



}
